import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';

const service = axios.create({
  baseURL: process.env.VUE_APP_BACKEND_DOMAIN,
  timeout: 20000,
  validateStatus: (status) => status >= 200 && status <= 500,
});

// HTTP request拦截
service.interceptors.request.use((config) => {
  config.params = config.params || {};
  config.headers = {
    'X-Requested-With': 'XMLHttpRequest',
  };

  if (config.method === 'get') {
    config.paramsSerializer = (params) => {
      return qs.stringify(params, { arrayFormat: 'repeat' });
    };
  }
  return config;
}, (error) => Promise.reject(error));

// HTTP response拦截
service.interceptors.response.use((res) => {
  const status = Number(res.status) || 200;
  const message = res.data.message || '服务器出错啦';

  if (status !== 200) {
    Message(message);
    return Promise.reject(new Error(res));
  }

  if (status === 200 && res.data.code !== 200) {
    Message(message);
    return Promise.reject(res);
  }

  return res.data?.data;
}, (error) => {
  handleResponseError(error)
  return Promise.reject(error);
});

const handleResponseError = (error) => {
  const response = error.response || {};
  if (response?.status) {
    switch (response.status) {
      case 400:
        Message(response.data.error_description || response.data.error || 'HTTP错误400 - 请求错误')
        break
      case 405:
        Message('请求方式不支持')
        break
      case 503:
        Message('服务器不可用，请稍后重试');
        break
      case 504:
        Message('HTTP错误504 - 连接超时');
        break
      default:
        Message('未知错误: ' + response.status);
    }
  } else {
    Message('未知错误');
  }
};

export default service;
